package com.dong.example.service;

import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import com.alibaba.fastjson.JSONObject;
import com.dong.es.entity.EsResult;
import com.dong.es.entity.searchparam.agg.EsAggsTermsParam;
import com.dong.es.service.EsService;
import com.dong.es.util.DateUtils;
import com.dong.example.entity.DemoESDO;
import com.dong.example.entity.DemoESDTO;
import com.dong.example.entity.DemoESViewDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2022-12-07 16:21
 */
@Service
public class EsTestService {

    @Autowired
    private EsService esService;

    public void demo() {
        // 创建用户操作参数
        DemoESViewDTO csmViewDTO = new DemoESViewDTO();

        csmViewDTO.setName("陈瑞东");
        csmViewDTO.setStartQueryTime(DateUtils.parseDate("2022-11-01"));
        csmViewDTO.setEndQueryTime(DateUtils.parseDate("2022-12-01"));
        csmViewDTO.setOrderBy(DemoESDTO.ID + " desc");
        csmViewDTO.setPageNo(1);
        csmViewDTO.setPageSize(1000);
        csmViewDTO.setEnabled(true);


        // 构建参数
        DemoESDTO params = csmViewDTO.build(new DemoESDTO());
        // 开始查询
        EsResult<List<DemoESDO>> esResult = esService.doQueryCommon(params, DemoESDO.class);

        // 查询到的数据
        List<DemoESDO> data = esResult.getData();

        // 聚合对象
        Map<String, Aggregate> aggregations = esResult.getAggregations();
        // 解析聚合
        List<EsAggsTermsParam.Result> aggregationResult = params.parseAggregations(aggregations, EsAggsTermsParam.class);

        // 总数
        Long total = esResult.getTotal();

        // 下一页排序号，searchAfter 可用
        List<String> searchAfter = esResult.getSearchAfter();

        // 打印数据
        System.out.println("=================================================");
        System.out.println("数据：");
        data.forEach(e -> System.out.println(JSONObject.toJSONStringWithDateFormat(e, "yyyy-MM-dd HH:mm:ss")));
        System.out.println("=================================================");
        System.out.println("聚合：");
        aggregationResult.forEach(System.out::println);
        System.out.println("=================================================");
        System.out.println("排序号：" + searchAfter);
        System.out.println("总数：" + total);
    }
}
